import { getFullNameReq } from '@/service/modules/department'
import { getUserInfoReq, updateUserHeadImgReq } from '@/service/modules/user'
import { UserInfo } from '@/service/modules/user/types'
import { reactive, Ref } from 'vue'
import { Response } from '@/service/modules/common/types'
import {
  createOrUpdateKAReq,
  getKeytabUrlReq
} from '@/service/modules/kerberos'
import { genAccessKeyReq, getAccessKeyReq } from '@/service/modules/data-api'

export function useUserCenter() {
  const variables = reactive({
    departmentFullName: ''
  })
  const getDepartmentFullName = async (id: number) => {
    const { data: res } = await getFullNameReq({ departmentId: id })
    variables.departmentFullName = res
  }
  const updateUserHeadImg = async (headImgUrl: string) => {
    const res = await updateUserHeadImgReq({ headImgUrl: headImgUrl })
    //更新用户信息缓存
    if (res.resp_code === 0) {
      const userInfoRes: Response<UserInfo> = await getUserInfoReq()
      window.$store.commit('updateUserInfo', userInfoRes.data)
    }
  }

  const genKeytab = async (keytabDownloadUrl: Ref<string>) => {
    const res = await createOrUpdateKAReq()
    if (res.resp_code === 0) {
      getKeytab(keytabDownloadUrl)
    }
  }
  const getKeytab = async (keytabDownloadUrl: Ref<string>) => {
    const res = await getKeytabUrlReq()
    if (res.data?.fileUrl) {
      keytabDownloadUrl.value = res.data?.fileUrl
    } else {
      keytabDownloadUrl.value = 'javascript:;'
    }
  }
  const genAccessKey = async (accessKey: Ref<string>) => {
    const res = await genAccessKeyReq()
    if (res.resp_code === 0) {
      getAccessKey(accessKey)
    }
  }
  const getAccessKey = async (accessKey: Ref<string>) => {
    const res = await getAccessKeyReq()
    if (res.data?.accessKey) {
      accessKey.value = res.data?.accessKey
    } else {
      accessKey.value = ''
    }
  }
  return {
    variables,
    getDepartmentFullName,
    updateUserHeadImg,
    genKeytab,
    getKeytab,
    genAccessKey,
    getAccessKey
  }
}
